package com.xinghai.web.controller.api;

import cn.dev33.satoken.stp.StpUtil;
import com.xinghai.common.constant.CacheConstants;
import com.xinghai.common.core.controller.BaseController;
import com.xinghai.common.core.domain.AjaxResult;
import com.xinghai.common.core.redis.RedisCache;
import com.xinghai.common.utils.DateUtils;
import com.xinghai.common.utils.PageUtils;
import com.xinghai.common.utils.StringUtils;
import com.xinghai.system.domain.*;
import com.xinghai.system.domain.entity.ReservationDTO;
import com.xinghai.system.domain.entity.SaleDTO;
import com.xinghai.system.domain.vo.QdStoreVo;
import com.xinghai.system.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.*;

/**
 * 钱包api接口
 *
 * @author xinghai
 * @date 2024-12-04
 */
@RestController
@RequestMapping("/api/order")
public class QdOrderApiController extends BaseController
{
    @Autowired
    private IQdUserService userService;
    @Autowired
    private IQdStoreService storeService;
    @Autowired
    private IQdOrderService orderService;

    @Autowired
    private IQdPayOrderService payOrderService;

    @Autowired
    private IQdPayOrderInfoService payOrderInfoService;

    @Autowired
    private RedisCache redisCache;



    /**
     * 查询订单模块列表
     */
    @GetMapping("/getInfo")
    public AjaxResult getInfo()
    {
        Long loginId = StpUtil.getLoginId(0L);
        QdUser user = userService.getById(loginId);
        QdOrder order = new QdOrder();
        order.setUserId(user.getId());
        order.setStoreId(user.getAscriptionStore());
        order.setStatus("0,2");
        List<QdOrder> list = orderService.list(order);
        int dzf = (int) list.stream().filter(m -> Objects.equals(m.getBuyerUserId(), order.getUserId()) && ((m.getBuyerStatus().equals("0")&&!m.getSellerStatus().equals("0")) || m.getBuyerStatus().equals("1"))).count();
        int dsj = (int) list.stream().filter(m -> Objects.equals(m.getBuyerUserId(), order.getUserId()) && m.getBuyerStatus().equals("2")).count();
        int sjdsh = (int) list.stream().filter(m -> Objects.equals(m.getBuyerUserId(), order.getUserId()) &&m.getBuyerStatus().equals("3")).count();
        int dcs = (int) list.stream().filter(m -> Objects.equals(m.getSellerUserId(), order.getUserId()) &&m.getSellerStatus().equals("0")).count();
        int dsk = (int) list.stream().filter(m -> Objects.equals(m.getSellerUserId(), order.getUserId()) &&m.getSellerStatus().equals("1")).count();
        int ywc = (int) list.stream().filter(m -> Objects.equals(m.getSellerUserId(), order.getUserId()) &&m.getSellerStatus().equals("2")).count();
        Map<String,Object> map = new HashMap<>();
        map.put("dzfData",dzf);//
        map.put("dsjData",dsj);
        map.put("sjdshData",sjdsh);
        map.put("dcsData",dcs);
        map.put("dskData",dsk);
        map.put("ywcData",ywc);
        return success(map);
    }

    /**
     * 查询店铺首页信息
     */
    @GetMapping("/getStoreIndexInfo")
    public AjaxResult getStoreIndexInfo()
    {
        String loginId = StpUtil.getLoginId("");
        QdUser user = userService.getByLoginId(loginId);
        QdStoreVo cacheMap = redisCache.getCacheObject(CacheConstants.STORE_INFO + user.getAscriptionStore());
        if (cacheMap==null){
            cacheMap = storeService.getIndexInfo(user.getAscriptionStore());
            redisCache.setCacheObject(CacheConstants.STORE_INFO + user.getAscriptionStore(), cacheMap);
        }
        return success(cacheMap);
    }

    /**
     * 预约订单
     */
    @PostMapping("/reservationOrder")
    public AjaxResult reservationOrder(@Validated @RequestBody ReservationDTO dto)
    {
        String loginId = StpUtil.getLoginId("");
        QdUser user = userService.getByLoginId(loginId);
        QdStoreVo cacheMap = redisCache.getCacheObject(CacheConstants.STORE_INFO + user.getAscriptionStore());
        if (cacheMap==null){
            cacheMap = storeService.getIndexInfo(user.getAscriptionStore());
            redisCache.setCacheObject(CacheConstants.STORE_INFO + user.getAscriptionStore(), cacheMap);
        }
        if (DateUtils.parseDate(cacheMap.getReservationStartDateDay()).compareTo(DateUtils.getNowDate())>-1||DateUtils.parseDate(cacheMap.getReservationEndDateDay()).compareTo(DateUtils.getNowDate())<0){
            return error("请在预约时间进行预约");
        }
        QdOrder yuyueOrder = new QdOrder();
        yuyueOrder.setBuyerUserId(user.getId());
        yuyueOrder.setBuyerType("1");
        yuyueOrder.setDealTime(new Date());
        if (!orderService.list(yuyueOrder).isEmpty()){
            return error("您已经参加过预约，请勿重复预约！");
        }
        QdOrder order = new QdOrder();
        if ("1".equals(dto.getGroupType())){
            order.setMinPrice(cacheMap.getGroupOneMinPrice());
            order.setMaxPrice(cacheMap.getGroupOneMaxPrice());
        }else if ("2".equals(dto.getGroupType())){
            order.setMinPrice(cacheMap.getGroupTwoMinPrice());
            order.setMaxPrice(cacheMap.getGroupTwoMaxPrice());
        }else {
            order.setMinPrice(cacheMap.getGroupThreeMinPrice());
            order.setMaxPrice(cacheMap.getGroupThreeMaxPrice());
        }
        order.setSellerStatus("0");
        order.setStatus("0");
        order.setStoreId(user.getAscriptionStore());
        List<QdOrder> list = orderService.list(order);
        if (list.isEmpty()){
            return error("没有可预约的订单");
        }
        QdOrder qdOrder = list.get(0);
        qdOrder.setBuyerType("1");

        BigDecimal bili = user.getGiftValue();
        if (bili==null){
            bili = cacheMap.getAppreciation();
        }
        qdOrder.setListingFee(qdOrder.getPrice().multiply(cacheMap.getListingFee()).divide(BigDecimal.valueOf(100), 2, RoundingMode.HALF_UP));
        qdOrder.setNewPrice(qdOrder.getPrice().multiply(bili.add(BigDecimal.valueOf(100))).divide(BigDecimal.valueOf(100), 2, RoundingMode.HALF_UP));
        qdOrder.setPushAmount(qdOrder.getPrice().multiply(cacheMap.getPushFee()).divide(BigDecimal.valueOf(100), 2, RoundingMode.HALF_UP));
        return success(orderService.addOrder(user,qdOrder));
    }

    /**
     * 抢购订单
     */
    @PostMapping("/saleOrder")
    public AjaxResult saleOrder(@Validated @RequestBody SaleDTO dto)
    {
        String loginId = StpUtil.getLoginId("");
        QdUser user = userService.getByLoginId(loginId);
        QdStoreVo cacheMap = redisCache.getCacheObject(CacheConstants.STORE_INFO + user.getAscriptionStore());
        if (cacheMap==null){
            cacheMap = storeService.getIndexInfo(user.getAscriptionStore());
            redisCache.setCacheObject(CacheConstants.STORE_INFO + user.getAscriptionStore(), cacheMap);
        }
        if (DateUtils.parseDate(cacheMap.getSaleStartDateDay()).compareTo(DateUtils.getNowDate())>-1||DateUtils.parseDate(cacheMap.getSaleEndDateDay()).compareTo(DateUtils.getNowDate())<0){
            return error("请在抢购时间进行抢购");
        }
        QdOrder qdOrder = orderService.getById(dto.getDataId());
        if (qdOrder==null|| !Objects.equals(qdOrder.getStoreId(), user.getAscriptionStore())){
            return error("订单发生变动，请刷新后重试！");
        }
        if (!"0".equals(qdOrder.getSellerStatus())){
            return error("此订单已被别人抢购");
        }
        //判断限额
        QdOrder order = new QdOrder();
        order.setBuyerUserId(user.getId());
        order.setBuyerType("2");
        order.setStatus("0");
        order.setDealTime(new Date());
        List<QdOrder> list = orderService.list(order);
        BigDecimal reduce = list.stream().map(QdOrder::getPrice).reduce(BigDecimal.ZERO, BigDecimal::add);
        BigDecimal saleQuota = cacheMap.getSaleQuota();
        if (saleQuota == null){
            saleQuota = new BigDecimal("35000");
        }
        if (reduce.add(qdOrder.getPrice()).compareTo(saleQuota)>0){
            return error("今日已达上限");
        }
        qdOrder.setBuyerType("2");
        BigDecimal bili = user.getGiftValue();
        if (bili==null){
            bili = cacheMap.getAppreciation();
        }
        qdOrder.setListingFee(qdOrder.getPrice().multiply(cacheMap.getListingFee()).divide(BigDecimal.valueOf(100), 2, RoundingMode.HALF_UP));
        qdOrder.setNewPrice(qdOrder.getPrice().multiply(bili.add(BigDecimal.valueOf(100))).divide(BigDecimal.valueOf(100), 2, RoundingMode.HALF_UP));
        qdOrder.setPushAmount(qdOrder.getPrice().multiply(cacheMap.getPushFee()).divide(BigDecimal.valueOf(100), 2, RoundingMode.HALF_UP));
        orderService.addOrder(user,qdOrder);
        return success();
    }

    /**
     * 查询抢购订单列表
     */
    @GetMapping("/getPanicBuyingList")
    public AjaxResult getPanicBuyingList(Integer pageNum,Integer pageSize)
    {
        String loginId = StpUtil.getLoginId("");
        QdUser user = userService.getByLoginId(loginId);
        PageUtils.startPage(pageNum,pageSize);
        PageUtils.orderBy("price desc");
        QdOrder order = new QdOrder();
        order.setSellerStatus("0");
        order.setStatus("0");
        order.setStoreId(user.getAscriptionStore());
        List<QdOrder> list = orderService.list(order);
        return success(getDataTable(list));
    }

    /**
     * 查询卖出订单列表
     */
    @GetMapping("/getSellerOrderList")
    public AjaxResult getSellerOrderList(Integer pageNum,Integer pageSize,String type)
    {
        String loginId = StpUtil.getLoginId("");
        QdUser user = userService.getByLoginId(loginId);
        PageUtils.startPage(pageNum,pageSize);
        PageUtils.orderBy("price desc");
        QdOrder order = new QdOrder();
        order.setSellerUserId(Long.valueOf(loginId));
        order.setSellerStatus(type);
        order.setStatus("0,2");
        //order.setDealTime(new Date());
        order.setStoreId(user.getAscriptionStore());
        List<QdOrder> list = orderService.list(order);
        return success(getDataTable(list));
    }
    /**
     * 查询买入订单列表
     */
    @GetMapping("/getBuyerOrderList")
    public AjaxResult getBuyerOrderList(Integer pageNum,Integer pageSize,String type)
    {
        String loginId = StpUtil.getLoginId("");
        QdUser user = userService.getByLoginId(loginId);
        PageUtils.startPage(pageNum,pageSize);
        PageUtils.orderBy("create_time desc");
        QdOrder order = new QdOrder();
        order.setStatus("0");
        order.setDealTime(new Date());
        order.setBuyerUserId(Long.valueOf(loginId));
        order.setStoreId(user.getAscriptionStore());
        if ("0".equals(type)||"1".equals(type)){
            order.setBuyerStatusStr("0,1");
        }else {
            order.setBuyerStatusStr(type);
        }
        List<QdOrder> list = orderService.list(order);
        return success(getDataTable(list));
    }

    /**
     * 生成对账单状态
     */
    @GetMapping("/getBuyerPayStatus")
    public AjaxResult getBuyerPayStatus()
    {
        String loginId = StpUtil.getLoginId("");
        QdUser user = userService.getByLoginId(loginId);
        QdPayOrder payOrder = new QdPayOrder();
        payOrder.setStoreId(user.getAscriptionStore());
        payOrder.setGenDate(DateUtils.getNowDate());
        List<QdPayOrder> list = payOrderService.list(payOrder);
        Map<String,Object> map = new HashMap<>();
        if (list.isEmpty()){
            map.put("payStatus","0");//0未生成1已生成
        }else {
            map.put("payStatus","1");//0未生成1已生成
            map.put("payOrderId",list.get(0).getId());//付款单id
        }
        return success(map);
    }
    /**
     * 上架费
     */
    @GetMapping("/getBuyerOrderInfo")
    public AjaxResult getBuyerOrderInfo(String type)
    {
        String loginId = StpUtil.getLoginId("");
        QdUser user = userService.getByLoginId(loginId);
        QdOrder qdOrder = new QdOrder();
        qdOrder.setStoreId(user.getAscriptionStore());
        qdOrder.setBuyerUserId(Long.valueOf(loginId));
        if ("0".equals(type)||"1".equals(type)){
            qdOrder.setBuyerStatusStr("0,1");
        }else {
            qdOrder.setBuyerStatusStr(type);
        }
        List<QdOrder> list = orderService.list(qdOrder);
        QdStore store = storeService.getById(user.getAscriptionStore());
        BigDecimal reduce = list.stream().map(QdOrder::getListingFee).reduce(BigDecimal.ZERO, BigDecimal::add);
        BigDecimal reduce1 = list.stream().map(m->m.getPrice().multiply(store.getGroupingFee()).divide(BigDecimal.valueOf(100), 2, RoundingMode.HALF_UP)).reduce(BigDecimal.ZERO, BigDecimal::add);
        Map<String,Object> map = new HashMap<>();
        map.put("listingFee",reduce);//上架费
        map.put("listingPoints",reduce1);//上架所需积分
        return success(map);
    }


    /**
     * 查询付款单详情
     */
    @GetMapping("/getPayOrderInfo")
    public AjaxResult getPayOrderInfo(String payOrderId,String dataId)
    {
        if (StringUtils.isEmpty(payOrderId)&&StringUtils.isEmpty(dataId)){
            return error("参数错误");
        }
        if (StringUtils.isNotBlank(dataId)){
            QdPayOrderInfo info = payOrderInfoService.getByDataId(dataId);
            return success(info);
        }
        String userId = StpUtil.getLoginId("");
        QdPayOrderInfo info = payOrderInfoService.getByPayOrderId(payOrderId,userId);
        return success(info);
    }

    /**
     * 确认平账状态
     */
    @GetMapping("/balanceStatus")
    public AjaxResult balanceStatus(String payOrderInfoId)
    {
        QdPayOrderInfo info = payOrderInfoService.getById(payOrderInfoId);
        return success("1".equals(info.getStatus()));
    }

    /**
     * 确认平账
     */
    @GetMapping("/confirmBalance")
    public AjaxResult confirmBalance(String payOrderInfoId)
    {
        String loginId = StpUtil.getLoginId("");
        QdPayOrderInfo info = payOrderInfoService.getById(payOrderInfoId);
        if (!loginId.equals(String.valueOf(info.getUserId()))){
            return error("请勿非法操作");
        }
        if ("1".equals(info.getStatus())){
            return error("已确认平账");
        }
        return success(payOrderInfoService.confirmBalance(info));
    }

    /**
     * 上架
     */
    @GetMapping("/updateListingStatus")
    public AjaxResult updateListingStatus(String orderId)
    {
        String loginId = StpUtil.getLoginId("");
        QdOrder info = orderService.getById(orderId);
        if (!loginId.equals(String.valueOf(info.getBuyerUserId()))){
            return error("请勿非法操作");
        }
        if (!"2".equals(info.getBuyerStatus())){
            return error("订单信息已变更，请刷新");
        }
        info.setBuyerStatus("3");
        return success(orderService.updateListingStatus(info));
    }
}
